# -*- coding:utf-8 -*-

from twisted.internet.protocol import Factory
from my_protocols import *
from API import config, check
import hashlib


def download(reactor):
    f = Factory()
    f.protocol = Download
    reactor.listenTCP(config['download']['port'], f)


def upload(reactor):
    f = Factory()
    f.protocol = Upload
    reactor.listenTCP(config['upload']['port'], f)


def cmd(reactor):
    f = Factory()
    f.protocol = Command
    reactor.listenTCP(config['command']['port'], f)


if __name__ == '__main__':
    import sys

    try:
        check()
    except Exception as err:
        print "Program files damaged, please reinstall"
        print str(err)
        sys.exit()

    from twisted.internet import reactor
    # 初始化数据库
    try:
        if sys.argv[1] == 'init':
            from orm import init
            from my_protocols.cmd import create_user

            init(config['init']['dir'])
            create_user(name=config['init']['user'], password=hashlib.sha1(config['init']['password']).hexdigest(),
                        info='admin!', is_admin=True)
    except IndexError:
        pass
    from orm.fst import check_connection
    check_connection()
    download(reactor)
    upload(reactor)
    cmd(reactor)
    print "Initialization Completed. Welcome to aerodb!"
    reactor.run()
